%%%-------------------------------------------------------------------
%%% @author Rain
%%% @doc 数据库升级器
%%% @end
%%%-------------------------------------------------------------------
-module(db_updater).
-author("Rain").
-include("db.hrl").


%% API
-export([check/1]).


%% @doc 数据库升级器检查
check(DBTypeList) ->
    {ok, ConnPid} = check_connect_db(),
    Fun = fun(DBType) -> check_db_one(DBType, ConnPid) end,
    lists:foreach(Fun, DBTypeList).

check_db_one(DBType, ConnPid) ->
    DBName = db_config:get_db_by_type(DBType),
    {ok, IsJustCreate} = check_db_exist(DBName, ConnPid),
    check_db_update(DBName, ConnPid, IsJustCreate).


check_connect_db() ->
    DBHost = db_config:get_cfg(db_host),
    DBPort = db_config:get_cfg(db_port),
    DBUser = db_config:get_cfg(db_user),
    DBPasswd = db_config:get_cfg(db_passwd),
    Args = [{host, DBHost}, {port, DBPort}, {user, DBUser},
        {password, DBPasswd}, {query_timeout, ?MYSQL_QUERY_TIMEOUT}],
    case mysql:start_link(Args) of
        {ok, Pid} ->
            {ok, Pid};
        _ ->
            ?LOG_ERROR("Connect DB fail args ~w, server will be shut down", [Args]),
            init:stop(1)
    end.

%% @doc 检查数据库是否存在，不存在则创建
check_db_exist(DBName, ConnPid) ->
    Sql = ["SHOW DATABASES LIKE ", "'", DBName, "';"],
    case mysql:query(ConnPid, Sql) of
        {ok, [_|_], [_|_]} ->
            ?LOG_INFO("DB ~s exist, no need to create.", [DBName]),
            {ok, ?false};
        {ok, _, _} ->
            CreateSql = ["CREATE DATABASE ", DBName, ";"],
            ?LOG_INFO("DB ~s not exist, system is trying to create.", [DBName]),
            case mysql:query(ConnPid, CreateSql) of
                ok ->
                    ?LOG_INFO("Create DB ~s success.", [DBName]),
                    {ok, ?true};
                Res ->
                    ?LOG_ERROR("Create DB ~s fail. Res ~p.", [DBName, Res]),
                    init:stop(1)
            end;
        {error, Reason} ->
            ?LOG_ERROR("Check DB ~s exist fail. Reson ~p.", [DBName, Reason]),
            init:stop(1);
        Any ->
            ?LOG_ERROR("Check DB ~s exist fail. Unknown Return ~p.", [DBName, Any]),
            init:stop(1)
    end.


%% @doc 检查数据库是否可以动态升级，可以则进行升级
check_db_update(_DBName, _ConnPid, ?true) ->
    pass;
check_db_update(DBName, ConnPid, _IsJustCreate) ->
    Sql = ["USE ", DBName, ";"],
    case mysql:query(ConnPid, Sql) of
        ok ->
            ?LOG_INFO("Use DB ~s Succ", [DBName]),
            ok;
        Any ->
            ?LOG_INFO("Any ~p", [Any])
    end.


